<template>
  <div class="login-container">
    <div class="login-box">
      <div class="logo-container">
        <div class="logo">登录</div>
      </div>
      <h2 class="title">欢迎回来</h2>
      <p class="subtitle">请输入您的账号信息</p>
      <el-form id="loginForm" autocomplete="on" @submit.prevent="handleLogin">
        <el-form-item :error="errors.username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            autocomplete="username"
            name="username"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item :error="errors.password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            autocomplete="current-password"
            name="password"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <div class="remember-box">
          <el-checkbox v-model="rememberMe" label="记住密码" />
          <el-checkbox v-model="autoLogin" label="自动登录" />
        </div>
        <el-form-item>
          <el-button type="primary" class="login-btn" :loading="loading" @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        <div class="register-link" @click="goToRegister">没有账号？去注册</div>
        <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon class="error-alert">
          <template
            v-if="encryptedMac && (errorMessage.includes('未授权') || errorMessage.includes('授权失败'))"
            #default
          >
            <el-button size="small" @click="copyMacAddress">复制授权码</el-button>
          </template>
        </el-alert>
      </el-form>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { login, getUserInfo } from '../api/user';
  import { saveUserInput, getUserInput } from '../utils/storage';
  import { saveCredentials, getCredentials, isAutoLoginEnabled, clearCredentials } from '../utils/autoLoginService';
  import CryptoJS from 'crypto-js';
  import { User, Lock } from '@element-plus/icons-vue';

  const router = useRouter();
  const loading = ref(false);
  const errorMessage = ref('');
  const encryptedMac = ref('');
  const rememberMe = ref(false);
  const autoLogin = ref(false);

  // 添加错误信息对象，用于存储每个字段的错误信息
  const errors = reactive({
    username: '',
    password: '',
  });

  // 登录表单数据
  const loginForm = reactive({
    username: '',
    password: '',
  });

  // 组件挂载时，从本地存储获取用户名和密码，并检查是否需要自动登录
  // 监听自动登录选项变化，当选择自动登录时自动勾选记住密码
  watch(autoLogin, (newValue) => {
    if (newValue === true) {
      rememberMe.value = true;
    }
  });

  onMounted(async () => {
    // 获取保存的凭据
    const savedCredentials = getCredentials();

    if (savedCredentials) {
      // 填充用户名和密码
      loginForm.username = savedCredentials.username;
      loginForm.password = savedCredentials.password;

      // 设置记住密码为true
      rememberMe.value = true;

      // 检查是否启用了自动登录
      autoLogin.value = isAutoLoginEnabled();

      // 如果启用了自动登录，自动执行登录
      if (autoLogin.value && !localStorage.getItem('token')) {
        // 延迟一下再自动登录，确保组件完全挂载
        setTimeout(() => {
          handleLogin();
        }, 500);
      }
    } else {
      // 如果没有保存的凭据，只获取用户名
      loginForm.username = getUserInput('username');
    }
  });

  // 处理登录
  const handleLogin = async () => {
    // 重置所有错误信息
    errors.username = '';
    errors.password = '';
    errorMessage.value = '';

    // 表单验证
    let hasError = false;

    if (!loginForm.username) {
      errors.username = '用户名不能为空';
      hasError = true;
    }
    // 用户名格式验证（只允许字母、数字和下划线，长度3-20）
    else if (!/^[a-zA-Z0-9_]{3,20}$/.test(loginForm.username)) {
      errors.username = '用户名只能包含字母、数字和下划线，长度3-20位';
      hasError = true;
    }

    if (!loginForm.password) {
      errors.password = '密码不能为空';
      hasError = true;
    }
    // 密码长度验证
    else if (loginForm.password.length < 6 || loginForm.password.length > 20) {
      errors.password = '密码长度必须在6-20位之间';
      hasError = true;
    }

    if (hasError) {
      return;
    }

    // 保存用户名到本地存储（不保存密码）
    saveUserInput('username', loginForm.username);

    try {
      loading.value = true;
      errorMessage.value = '';

      // 获取MAC地址
      let device_mac_md5 = '';
      try {
        const { api } = window;
        if (api && api.getMacAddress) {
          // 对MAC地址进行MD5加密
          device_mac_md5 = CryptoJS.MD5(await api.getMacAddress()).toString();
          // 保存加密后的MAC地址，用于复制功能
          encryptedMac.value = device_mac_md5;
        }
      } catch (error) {
        console.error('获取MAC地址失败:', error);
      }

      // 构建登录数据，与Python测试代码一致
      const loginData = {
        username: loginForm.username,
        password: loginForm.password,
        device_mac: device_mac_md5, // 添加MD5加密后的MAC地址
      };

      const res = await login(loginData);

      if (res.access_token) {
        // 登录成功，保存token和用户信息
        localStorage.setItem('token', res.access_token);

        // 获取用户信息
        const userInfo = await getUserInfo();

        // 验证token一致性和检查过期时间
        if (userInfo && userInfo.access_token) {
          // 比较getUserInfo返回的access_token与登录接口返回的token是否一致
          if (userInfo.access_token !== res.access_token) {
            errorMessage.value = '未授权：Token不一致';
            // 清空缓存
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            loading.value = false;
            return;
          }

          // 检查token是否过期
          if (userInfo.expire_time) {
            const expireDate = new Date(userInfo.expire_time);
            const currentDate = new Date();

            if (expireDate < currentDate) {
              errorMessage.value = '未授权：授权已过期';
              // 清空缓存
              localStorage.removeItem('token');
              localStorage.removeItem('userInfo');
              loading.value = false;
              return;
            }
          }
        }

        localStorage.setItem('userInfo', JSON.stringify(userInfo));

        // 如果用户选择了记住密码，保存凭据
        if (rememberMe.value) {
          // 保存用户凭据（包括密码）
          saveCredentials(
            {
              username: loginForm.username,
              password: loginForm.password,
            },
            autoLogin.value, // 是否启用自动登录
          );
        } else {
          // 如果没有选择记住密码，清除之前保存的凭据
          clearCredentials();
        }

        // 通知主进程用户已登录
        const { api } = window;
        if (api) {
          api.loginStatusChanged(true);
        }

        // 跳转到主页
        router.push('/main');
      } else {
        errorMessage.value = res.detail || '登录失败';
      }
    } catch (error) {
      console.error('登录错误:', error);
      errorMessage.value = '登录失败，请稍后重试';
    } finally {
      loading.value = false;
    }
  };

  // 跳转到注册页
  const goToRegister = () => {
    router.push('/register');
  };

  // 复制MAC地址加密值
  const copyMacAddress = () => {
    if (encryptedMac.value) {
      navigator.clipboard
        .writeText(encryptedMac.value)
        .then(() => {
          alert('授权码已复制到剪贴板，请联系管理员授权');
        })
        .catch((err) => {
          console.error('复制失败:', err);
          alert('复制失败，请联系管理员');
        });
    }
  };
</script>

<style lang="less" scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);

    .login-box {
      width: 420px;
      padding: 35px;
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &:hover {
        box-shadow: 0 16px 32px rgba(0, 0, 0, 0.18);
      }

      .logo-container {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;

        .logo {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          background: var(--el-color-primary);
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          font-weight: bold;
          box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);
        }
      }

      .title {
        text-align: center;
        margin-bottom: 8px;
        color: #333;
        font-size: 24px;
        font-weight: 600;
      }

      .subtitle {
        text-align: center;
        color: #909399;
        margin-bottom: 25px;
        font-size: 14px;
      }

      :deep(.el-form-item) {
        margin-bottom: 22px;
      }

      :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 1px #e0e3e9 inset;
        border-radius: 8px;
        padding: 0 15px;
        transition: all 0.3s ease;
        height: 45px;

        &.is-focus {
          box-shadow:
            0 0 0 1px var(--el-color-primary) inset,
            0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
        }

        &:hover {
          box-shadow:
            0 0 0 1px var(--el-color-primary) inset,
            0 0 0 3px rgba(var(--el-color-primary-rgb), 0.05);
        }
      }

      :deep(.el-input__inner) {
        height: 45px;
      }

      :deep(.el-form-item__error) {
        padding-top: 4px;
        font-size: 12px;
      }

      .remember-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 22px;
        padding: 0 2px;

        :deep(.el-checkbox__label) {
          font-size: 14px;
          color: #606266;
        }

        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          box-shadow: 0 2px 6px rgba(var(--el-color-primary-rgb), 0.2);
        }
      }

      .login-btn {
        width: 100%;
        height: 45px;
        font-size: 16px;
        font-weight: 500;
        border-radius: 8px;
        margin-top: 10px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);
        }
      }

      .register-link {
        text-align: center;
        color: var(--el-color-primary);
        cursor: pointer;
        margin: 20px 0;
        font-size: 14px;
        transition: all 0.2s ease;

        &:hover {
          color: var(--el-color-primary-dark-2);
          transform: translateY(-1px);
        }
      }

      .error-alert {
        margin-top: 15px;
        border-radius: 8px;

        :deep(.el-button) {
          margin-left: 10px;
        }
      }
    }
  }

  @media (max-width: 480px) {
    .login-box {
      width: 90%;
      padding: 25px;
    }
  }
</style>
